package com.zahb.qadx.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.githang.statusbar.StatusBarCompat;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.Curriculum;
import com.zahb.qadx.model.CurriculumChapter;
import com.zahb.qadx.model.MaterialInfo;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.net.RetrofitStudyTimeService;
import com.zahb.qadx.ui.activity.topic.ImgStr;
import com.zahb.qadx.ui.adapter.ChapterAdapter;
import com.zahb.qadx.ui.fragment.CurriculumDetailsFragment;
import com.zahb.qadx.ui.fragment.CurriculumTreeInfoFragment;
import com.zahb.qadx.ui.fragment.MediaPlayerFragment;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.ImageLoaderKt;
import com.zahb.qadx.util.Tips;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
//课程详情
public class CurriculumDetailsActivity extends BaseActivity
        implements MediaPlayerFragment.onFullHalfViewClickListener, MediaPlayerFragment.onStateChangedListener {

    @BindView(R.id.container_layout)
    ConstraintLayout mContainerLayout;
    @BindView(R.id.iv_media_bg)
    AppCompatImageView mIvMediaBg;
    @BindView(R.id.media_container)
    FrameLayout mMediaContainer;
    @BindView(R.id.book_container)
    FrameLayout mBookContainer;
    @BindView(R.id.tv_book)
    WebView mTvBook;
    @BindView(R.id.iv_full_half)
    AppCompatImageView mIvFullHalf;
    @BindView(R.id.media_bottom_container)
    CoordinatorLayout mMediaBottomContainer;
    @BindView(R.id.app_bar_layout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.tv_title)
    AppCompatTextView mTvTitle;
    @BindView(R.id.tv_sub_title)
    AppCompatTextView mTvSubTitle;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.tv_tab3)
    AppCompatTextView mTvTab3;
    @BindView(R.id.tv_tab4)
    AppCompatTextView mTvTab4;
    @BindView(R.id.view_pager2)
    ViewPager2 mViewPager2;

    private String[] mTabTitles = new String[]{"目录", "详情", "资料", "评论"};
    private Fragment[] mFragments = new Fragment[2];

    private ConstraintSet mPortraitConstraintSet;
    private ConstraintSet mLandscapeConstraintSet;

    private View mDecorView;
    private int mDefaultOption;
    private int mNavigationBarColor;

    private MediaPlayerFragment mFragment;

    private boolean mIsBookHalf = true;

    public Curriculum mCurriculum;

    public String relationshipId;
    private String relationshipType;
    private String  dataFromHtml;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        LiveEventBus.get(Constant.KEY_VIDEO_ID, MaterialInfo.class)
                .observe(this, materialInfo -> {
                    if (materialInfo.getType() == 1 || materialInfo.getType() == 2) {// 音视频
                        mBookContainer.setVisibility(View.GONE);
                        getLearnRecord(materialInfo);
                    } else if (materialInfo.getType() == 3) {// 图书
                        mIsBookHalf = true;
                        mBookContainer.setVisibility(View.VISIBLE);
//                        mTvBook.setText(Html.fromHtml(materialInfo.getContent()));
//        ImgStr.getWebview(webView,this,ImgStr.getImgStr(data));
                        dataFromHtml=materialInfo.getContent();
                        jsSupport(mTvBook,materialInfo.getContent());
                        NestedScrollView scrollView = (NestedScrollView) mTvBook.getParent();
                        scrollView.scrollTo(0, 0);
                        Fragment fragment = getSupportFragmentManager().findFragmentByTag("MediaPlayerFragment");
                        if (fragment instanceof MediaPlayerFragment)
                            getSupportFragmentManager().beginTransaction().remove(fragment).commitAllowingStateLoss();
                        mFragment = null;

                        CurriculumChapter chapter = getStudyChapter(false);
                        if (mCurriculum != null && chapter != null) {
                            saveStudyTimeBook(mCurriculum, chapter);
                        }

                    } else {
                    }

                });
    }
    // WebView 权限
    public void jsSupport(WebView webView, String data) {
//
//        WebSettings webSettings = webView.getSettings();
////
////        webSettings.setUseWideViewPort(true);
////        webSettings.setLoadWithOverviewMode(true);
////        webSettings.setUseWideViewPort(true);  //将图片调整到适合webview的大小
////        webSettings.setTextZoom(270);//设置H5页面中字体大小不跟随手机系统
//
//
//
//        webView.setBackgroundColor(0);
////        ImgStr.getWebview(webView,this,ImgStr.getImgStr(data));
//        webView.loadDataWithBaseURL(null,  data, "text/html", "utf-8", null);

        WebSettings settings = webView.getSettings();
        settings.setLoadWithOverviewMode(true);//设置WebView是否使用预览模式加载界面。
        webView.setVerticalScrollBarEnabled(false);//不能垂直滑动
        webView.setHorizontalScrollBarEnabled(false);//不能水平滑动
        settings.setTextSize(WebSettings.TextSize.NORMAL);//通过设置WebSettings，改变HTML中文字的大小
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过JS打开新窗口
        settings.setAllowUniversalAccessFromFileURLs(true);
        settings.setAllowFileAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
//设置WebView属性，能够执行Javascript脚本
        webView.getSettings().setJavaScriptEnabled(true);//设置js可用
        webView.setWebViewClient(new WebViewClient());
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        data = "<html><body>" + data + "</body></html>";
        String js = "<script type=\"text/javascript\">" +
                "var imgs = document.getElementsByTagName('img');" + // 找到img标签
                "for(var i = 0; i<imgs.length; i++){" +  // 逐个改变
                "imgs[i].style.width = '100%';" +  // 宽度改为100%
                "imgs[i].style.height = 'auto';" +
                "}" +
                "</script>";
        webView.loadDataWithBaseURL(null, ImgStr.getImgStr("<p style='font-size:18px;text-align:center;'>" + "" + "</p>" + data + js), "text/html; charset=UTF-8", "utf-8", null);

    }
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            mTopBarContainer.setVisibility(View.VISIBLE);
            mTopBarDivider.setVisibility(View.VISIBLE);
            mMediaBottomContainer.setVisibility(View.VISIBLE);
            mPortraitConstraintSet.applyTo(mContainerLayout);
            mDecorView.setSystemUiVisibility(mDefaultOption);
            getWindow().setNavigationBarColor(mNavigationBarColor);
            StatusBarCompat.setStatusBarColor(this, Color.WHITE);
        } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTopBarContainer.setVisibility(View.GONE);
            mTopBarDivider.setVisibility(View.GONE);
            mMediaBottomContainer.setVisibility(View.GONE);
            mLandscapeConstraintSet.applyTo(mContainerLayout);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            mDecorView.setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            StatusBarCompat.setStatusBarColor(this, Color.TRANSPARENT);
        }
    }

    @Override
    public void onBackPressed() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_curriculum_details;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mTopBarDivider.setVisibility(View.VISIBLE);
        mTopBarDivider.setBackgroundColor(CompatHelper.getColor(R.color.gray_999999));
        Curriculum curriculum = (Curriculum) getIntent().getSerializableExtra("curriculum");
        if (curriculum != null) {

            relationshipId = curriculum.getRelationshipId();
            relationshipType = curriculum.getRelationshipType();
            ImageLoaderKt.loadImage(mIvMediaBg, curriculum.getCoverImage());
            mTvTitle.setText(curriculum.getName());
            mTvSubTitle.setText(CompatHelper.isEmpty(curriculum.getSubName()) ? curriculum.getName() : curriculum.getSubName());
            mTvTab3.setText(mTabTitles[2]);
            mTvTab3.setVisibility(View.GONE);
            mTvTab4.setText(mTabTitles[3]);
            mTvTab4.setVisibility(View.GONE);
            // TODO: 2021/4/1 vivo 上架暂时注掉
            int from = getIntent().getIntExtra("from", -1);
            loadCurriculumDetails(curriculum, from);
        }

        initConstraintSets();

        mDecorView = getWindow().getDecorView();
        mDefaultOption = mDecorView.getSystemUiVisibility();
        mNavigationBarColor = getWindow().getNavigationBarColor();
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.curriculum_details;
    }

    private void initConstraintSets() {
        mPortraitConstraintSet = new ConstraintSet();
        mPortraitConstraintSet.clone(mContainerLayout);

        mLandscapeConstraintSet = new ConstraintSet();
        mLandscapeConstraintSet.clone(mContainerLayout);

        mLandscapeConstraintSet.clear(R.id.iv_media_bg);
        mLandscapeConstraintSet.connect(R.id.iv_media_bg, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        mLandscapeConstraintSet.connect(R.id.iv_media_bg, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
        mLandscapeConstraintSet.connect(R.id.iv_media_bg, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        mLandscapeConstraintSet.connect(R.id.iv_media_bg, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);

        mLandscapeConstraintSet.clear(R.id.media_container);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        mLandscapeConstraintSet.connect(R.id.media_container, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
    }

    public static final int TYPE_FROM_HOME = 1;
    public static final int TYPE_FROM_TASK = 2;

    public static void actionStart(Context context, Curriculum curriculum, int from) {
        Intent intent = new Intent(context, CurriculumDetailsActivity.class);
        intent.putExtra("curriculum", curriculum);
        intent.putExtra("from", from);
        context.startActivity(intent);
    }

    @OnClick({R.id.tv_tab3, R.id.tv_tab4, R.id.iv_full_half})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tab3:
            case R.id.tv_tab4:
                showBindToast("该功能暂未开放");
                break;
            case R.id.iv_full_half:
                if (mIsBookHalf) {
                    mIsBookHalf = false;
                    ConstraintSet set = new ConstraintSet();
                    set.clone(mContainerLayout);
                    set.connect(R.id.book_container, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
                    set.applyTo(mContainerLayout);
                    mIvFullHalf.setImageResource(R.drawable.ic_book_half);
                } else {
                    mIsBookHalf = true;
                    ConstraintSet set = new ConstraintSet();
                    set.clone(mContainerLayout);
                    set.connect(R.id.book_container, ConstraintSet.BOTTOM, R.id.media_container, ConstraintSet.BOTTOM);
                    set.applyTo(mContainerLayout);
                    mIvFullHalf.setImageResource(R.drawable.ic_book_full);

                }
                break;
        }
    }

    @Override
    public void onRequestFull(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void onRequestHalf(ImageView view) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    private void loadCurriculumDetails(Curriculum curriculum, int from) {
        int listType;
        if (from == CurriculumDetailsActivity.TYPE_FROM_HOME) {
            listType = 2;
        } else if (from == CurriculumDetailsActivity.TYPE_FROM_TASK) {
            listType = 1;
        } else {
            return;
        }
       // 获取课程信息
        addDisposable(RetrofitService.getNetService()
                .getCurriculumDetails(curriculum.getId() + "", curriculum.getSnapshotId(), curriculum.getCourseUserId(), listType)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    mCurriculum = response.getData();
                    mTvTitle.setText(mCurriculum.getName());
                    mTvSubTitle.setText(CompatHelper.isEmpty(mCurriculum.getSubName()) ? mCurriculum.getName() : mCurriculum.getSubName());
                    mCurriculum.setCourseUserId(curriculum.getCourseUserId());
                    mViewPager2.setAdapter(new CurriculumDetailsFragmentAdapter(
                            getSupportFragmentManager(), getLifecycle(), mFragments, mCurriculum, from));
                    mViewPager2.setOffscreenPageLimit(mFragments.length - 1);
                    mViewPager2.setUserInputEnabled(false);
                    TabLayoutMediator mediator = new TabLayoutMediator(
                            mTabLayout, mViewPager2, false, true, (tab, position) ->
                            tab.setText(mTabTitles[position]));
                    mediator.attach();
                }, Throwable::printStackTrace)
        );
    }

    private void getLearnRecord(MaterialInfo materialInfo) {
        CurriculumChapter chapter = getStudyChapter(false);
        if (mCurriculum != null && chapter != null) {
            addDisposable(RetrofitService.getNetService()
                    .getLearnRecord(chapter.getId() + "",relationshipId==null ? "0":relationshipId, mCurriculum.getCourseUserId())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        int playedTime = 0;
                        if (response.getStatusCode() == 200) {
                            playedTime = (int) response.getData().getPlayedTime();
                        }
                        Fragment fragment = getSupportFragmentManager().findFragmentByTag("MediaPlayerFragment");
                        if (fragment instanceof MediaPlayerFragment)
                            mFragment = (MediaPlayerFragment) fragment;
                        if (mFragment == null) {
                            mFragment = MediaPlayerFragment.newInstance(
                                    materialInfo.getSourceId(), materialInfo.getType() == 2, playedTime);
                            mFragment.setOnFullHalfViewClickListener(CurriculumDetailsActivity.this);
                            mFragment.setOnStateChangedListener(CurriculumDetailsActivity.this);
                            getSupportFragmentManager().beginTransaction().replace(R.id.media_container, mFragment, "MediaPlayerFragment").commitAllowingStateLoss();
                        } else {
                            mFragment.changeMedia(materialInfo.getSourceId(), materialInfo.getType() == 2, playedTime);
                        }
                    }, throwable -> {
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                    }));
        }
    }

    @Override
    public void onPause(int playedTime, int totalTime) {
        CurriculumChapter chapter = getStudyChapter(false);
        if (mCurriculum != null && chapter != null) {
            saveStudyTime(playedTime, totalTime, mCurriculum, chapter);
        }
    }

    @Override
    public void onChangeMedia(int playedTime, int totalTime) {
        CurriculumChapter chapter = getStudyChapter(true);
        if (mCurriculum != null && chapter != null) {
            if (TextUtils.equals(chapter.getMaterialType(), "1") || TextUtils.equals(chapter.getMaterialType(), "2")) {
                saveStudyTime(playedTime, totalTime, mCurriculum, chapter);
            }
        }
    }

    @Override
    public void onCompletion(int playedTime, int totalTime) {
        CurriculumChapter chapter = getStudyChapter(false);
        if (mCurriculum != null && chapter != null) {
            saveStudyTime(playedTime, totalTime, mCurriculum, chapter);
        }
    }

    private CurriculumChapter getStudyChapter(boolean isChangeMedia) {
        Fragment fragment = mFragments[0];
        if (fragment instanceof CurriculumTreeInfoFragment) {
            CurriculumTreeInfoFragment treeInfoFragment = (CurriculumTreeInfoFragment) fragment;
            ChapterAdapter chapterAdapter = treeInfoFragment.mChapterAdapter;
            if (isChangeMedia)
                return chapterAdapter.getPreCurriculumChapter();
            else
                return chapterAdapter.getCurriculumChapter();
        }
        return null;
    }

    private Gson mGson = new Gson();

    public void saveStudyTimeBook(Curriculum curriculum, CurriculumChapter chapter) {
        Map<String, Object> params = new HashMap<>();

        Map<String, Object> actor = new HashMap<>();
        actor.put("actorId", BaseApplication.getContext().getDataLogin().getUser().getId());
        actor.put("actorType", 1);// 用户类型【1：学生 2：老师】
        params.put("actor", actor);

        Map<String, Object> extensions = new HashMap<>();
        extensions.put("organizationId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        params.put("extensions", extensions);

        Map<String, Object> verbInfo = new HashMap<>();
        verbInfo.put("verbType","watched" );
        params.put("verbInfo", verbInfo);

        Map<String, Object> context = new HashMap<>();
        context.put("terminalInfo","APP");
        context.put("terminalType","2");
        Map<String, Object> extensions1 = new HashMap<>();
        extensions1.put("courseId", curriculum.getId());
        extensions1.put("courseOutlineId", chapter.getId());
        extensions1.put("courseSnapshotId", curriculum.getSnapshotId());
        extensions1.put("materialType", chapter.getMaterialType());
        extensions1.put("userCourseId", curriculum.getCourseUserId());
        extensions1.put("learnHours", chapter.getPeriod());

        context.put("extensions", extensions1);
        params.put("context", context);

        Map<String, Object> objectInfo = new HashMap<>();
        Map<String, Object> extensions2 = new HashMap<>();
        extensions2.put("objIdType", 0);// 0:素材快照id,1:素材id
        String objId = chapter.getMaterialSnapshotId();
        if (TextUtils.isEmpty(objId)) {
            extensions2.put("objIdType", 1);
            objId = chapter.getMaterialId();
        }
        int from = getIntent().getIntExtra("from", -1);
        if (from == TYPE_FROM_TASK)
            extensions2.put("source", 1);// 1:我的页面,2:其他
        else
            extensions2.put("source", 2);

        if (TextUtils.isEmpty(relationshipId)) {
            extensions2.put("relationshipId", "");
            extensions2.put("relationshipType", "1");
        } else {
            extensions2.put("relationshipId", relationshipId);
            extensions2.put("relationshipType", relationshipType);
        }

        objectInfo.put("extensions", extensions2);
        objectInfo.put("objId", objId);
        params.put("objectInfo", objectInfo);

        String json = mGson.toJson(params);
        postSaveStudyTime(json);
    }

    private void saveStudyTime(int playedTime, int totalTime, Curriculum curriculum, CurriculumChapter chapter) {
        Map<String, Object> params = new HashMap<>();

        Map<String, Object> actor = new HashMap<>();
        actor.put("actorId", BaseApplication.getContext().getDataLogin().getUser().getId());
        actor.put("actorType", 1);// 用户类型【1：学生 2：老师】
        params.put("actor", actor);

        Map<String, Object> extensions = new HashMap<>();
        extensions.put("organizationId", BaseApplication.getContext().getDataLogin().getCurrentOrg());
        params.put("extensions", extensions);

        Map<String, Object> verbInfo = new HashMap<>();
        verbInfo.put("verbType","watched" );
        params.put("verbInfo", verbInfo);

        Map<String, Object> context = new HashMap<>();
        context.put("terminalInfo","APP");
        context.put("terminalType","2");
        Map<String, Object> extensions1 = new HashMap<>();
        extensions1.put("courseId", curriculum.getId());
        extensions1.put("courseOutlineId", chapter.getId());
        extensions1.put("courseSnapshotId", curriculum.getSnapshotId());
        extensions1.put("materialType", chapter.getMaterialType());
        extensions1.put("playedTime", playedTime);
        extensions1.put("totalTime", totalTime);
        extensions1.put("userCourseId", curriculum.getCourseUserId());

        context.put("extensions", extensions1);
        params.put("context", context);

        Map<String, Object> objectInfo = new HashMap<>();
        Map<String, Object> extensions2 = new HashMap<>();
        extensions2.put("objIdType", 0);// 0:素材快照id,1:素材id
        String objId = chapter.getMaterialSnapshotId();
        if (TextUtils.isEmpty(objId)) {
            extensions2.put("objIdType", 1);
            objId = chapter.getMaterialId();
        }
        int from = getIntent().getIntExtra("from", -1);
        if (from == TYPE_FROM_TASK)
            extensions2.put("source", 1);// 1:我的页面,2:其他
        else
            extensions2.put("source", 2);

        if (TextUtils.isEmpty(relationshipId)) {
            extensions2.put("relationshipId", "");
            extensions2.put("relationshipType", "1");
        } else {
            extensions2.put("relationshipId", relationshipId);
            extensions2.put("relationshipType", relationshipType);
        }

        objectInfo.put("extensions", extensions2);
        objectInfo.put("objId", objId);
        params.put("objectInfo", objectInfo);

        String json = mGson.toJson(params);
        postSaveStudyTime(json);
    }

    private void postSaveStudyTime(String json) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), json);
        RetrofitStudyTimeService.sCollectionType = RetrofitStudyTimeService.sCollectionTypeVideo;
        Disposable disposable = RetrofitStudyTimeService.getNetService().saveStudyTime(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {

                }, Throwable::printStackTrace);
        addDisposable(disposable);
    }

    private static class CurriculumDetailsFragmentAdapter extends FragmentStateAdapter {

        private Fragment[] mFragments;
        private Curriculum mCurriculum;
        private int mFrom;

        CurriculumDetailsFragmentAdapter(@NonNull FragmentManager fragmentManager,
                                         @NonNull Lifecycle lifecycle, Fragment[] fragments,
                                         Curriculum curriculum, int from) {
            super(fragmentManager, lifecycle);
            mFragments = fragments;
            mCurriculum = curriculum;
            mFrom = from;
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            if (mFragments[position] == null) {
                if (position == 0) {
                    mFragments[position] = CurriculumTreeInfoFragment.newInstance(mCurriculum, mFrom);
                } else if (position == 1) {
                    mFragments[position] = CurriculumDetailsFragment.newInstance(mCurriculum, mFrom);
                }
            }
            return mFragments[position];
        }

        @Override
        public int getItemCount() {
            return mFragments.length;
        }
    }
}
